#include "facecat/stdafx.h"
#include "DataCenter.h"
#include "SecurityService.h"
#include "LatestServiceClient.h"
#include "HistoryServiceClient.h"
#include "PriceDataServiceClient.h"
#include "facecat/FCClientService.h"

String m_mainIP = L"110.42.188.197";
static int m_mainPort = 9956;

/*
 * 码表服务
 */
static SecurityService *m_securityService = 0;
/*
 * 最新数据服务
 */
static LatestServiceClient *m_latestServiceClient = 0;
/*
 * 历史数据服务
 */
static HistoryServiceClient *m_historyServiceClient = 0;
/*
 * 报价服务
 */
static PriceDataServiceClient *m_priceDataServiceClient = 0;

SecurityService* DataCenter::getSecurityService(){
    return m_securityService;
}

LatestServiceClient* DataCenter::getLatestServiceClient(){
    return m_latestServiceClient;
}

HistoryServiceClient* DataCenter::getHistoryServiceClient(){
    return m_historyServiceClient;
}

PriceDataServiceClient* DataCenter::getPriceDataServiceClient(){
    return m_priceDataServiceClient;
}

void DataCenter::startService() {
    m_securityService = new SecurityService;
    m_latestServiceClient = new LatestServiceClient ;
    FCClientService::addService(m_latestServiceClient);
    m_historyServiceClient = new HistoryServiceClient ;
    FCClientService::addService(m_historyServiceClient);
    m_priceDataServiceClient = new PriceDataServiceClient ;
    FCClientService::addService(m_priceDataServiceClient);
}

void* connectThread(Object lpParam){
    char token[4] = {0};
    int socketID = FCClientService::connectToServer(0, FCTran::StringTostring(m_mainIP).c_str(), m_mainPort, "", 0, "", "", "", 6000, token);
    if (socketID != -1)
    {
        m_latestServiceClient->setSocketID(socketID);
        m_historyServiceClient->setSocketID(socketID);
        m_priceDataServiceClient->setSocketID(socketID);
        m_latestServiceClient->m_connected = true;
        m_historyServiceClient->reqDevideDatas(FCClientService::getRequestID());
        m_historyServiceClient->reqCodes(FCClientService::getRequestID());
    }
    return 0;
}

void DataCenter::startConnect(){
    pthread_t recvThread;
    pthread_create(&recvThread, 0, connectThread, 0);
    int tick = 1000;
    while (!m_securityService->isLoaded())
    {
        ::sleep(1);
        tick--;
        if (tick < 0)
        {
            break;
        }
    }
}


